package com.starbaba.core.utils.json;

import java.text.SimpleDateFormat;
import java.util.Date;

import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

import com.tuanzi.server.loan_base.util.DateFormatFactory;

/**
 * JSON日期类型值处理器
 *
 * @Copyright: Copyright (c) 2006
 * @Company: Revenco Tech Ltd.
 * @anthor chenminhui<chenminhui@revenco.com>
 * @since 2012-2-14 上午08:46:48
 * @version V1.0
 */
public class JsonDateValueProcessor implements JsonValueProcessor {
	
	protected SimpleDateFormat dateFormater;
	
	public JsonDateValueProcessor() {
		dateFormater = DateFormatFactory.getDefaultDateFormat();
	}

	public JsonDateValueProcessor(String sDateFormater) {
		dateFormater = DateFormatFactory.getInstance(sDateFormater);
	}

	/* (non-Javadoc)
	 * @see net.sf.json.processors.JsonValueProcessor#processArrayValue(java.lang.Object, net.sf.json.JsonConfig)
	 * 处理数组中日期类型值
	 */
	@Override
	public Object processArrayValue(Object value, JsonConfig jsonconfig) {
		if(value == null) {
			return value;
		}
		return dateFormater.format(getDate(value));
	}

	/* (non-Javadoc)
	 * @see net.sf.json.processors.JsonValueProcessor#processObjectValue(java.lang.String, java.lang.Object, net.sf.json.JsonConfig)
	 * 处理对象Object中的日期类型值
	 */
	@Override
	public Object processObjectValue(String s, Object value, JsonConfig jsonconfig) {
		if(value == null) {
			return value;
		}
		return dateFormater.format(getDate(value));
	}
	
	private Date getDate(Object value) {
		Date date = null;
		if(value instanceof java.sql.Date) {
			date = new Date(((java.sql.Date) value).getTime());
		} else {
			date = (Date)value;
		}
		return date;
	}
}
